import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
import django 
django.setup()

from django.conf import settings
from backend.gnsuser.models import GnsUser
from backend.gnsuser.gnsuser import GnsuserAPI
from django.contrib.auth import get_user_model

User = get_user_model()

user_api = GnsuserAPI()

data,res = user_api.getAll()

# print(data)

users = User.objects.all()
users_dict = {
    u.username:u
    for u in users
}

count =0

for row in data:
    qrcode= row['qrcode']
    username = row['username']
    services = row['services']
    
    if 'mtrqr' in services:

        user = users_dict.get(username,None)
        ## update exist user
        if user:
            # print(row)
            print(services)
            if 'mtrqr' in services:
                print( services['mtrqr']['last_name'])
                user = User.objects.get(username=user)
                print(user)
                if 'last_name' in services['mtrqr']:
                    user.last_name = services['mtrqr']['last_name']
                if 'first_name' in services['mtrqr']:
                    user.first_name = services['mtrqr']['first_name']
                if 'email' in services['mtrqr']:
                    user.email = services['mtrqr']['email']
                user.save()
  
        # import user when no user
        # if user is None:
        #     print(row)
        #     staff_code = ''
            
        #     ## try to get staff code 
        #     if 'profile' in  services and 'staffcode' in services['profile']:
        #         staff_code = services['profile']['staffcode']
            
        #     users_dict[username] = 1
        #     user = User.objects.create_user(username=username,staffNo=staff_code)
        #     user.set_password('Gns@2023')
        #     user.save()
        #     GnsUser.objects.create(user=user,qrcode=qrcode)
        